import React, { useState, useEffect } from "react";
import {
  Card,
  List,
  Space,
  Button,
  Tag,
  Input,
  Select,
  Modal,
  message,
  Form,
  Typography,
  Avatar,
  Tooltip,
  Empty,
  Spin,
  Tabs,
  Alert,
  Row,
  Col,
  Statistic,
  Badge,
  Divider,
  Dropdown,
  Popconfirm,
} from "antd";
import {
  MessageOutlined,
  LikeOutlined,
  LikeFilled,
  EyeOutlined,
  UserOutlined,
  RobotOutlined,
  PushpinOutlined,
  SendOutlined,
  ExclamationCircleOutlined,
  CrownOutlined,
  BookOutlined,
  TeamOutlined,
  StarOutlined,
  DeleteOutlined,
  EditOutlined,
  MoreOutlined,
  FlagOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionFilter,
  DiscussionReply,
} from "../../common/types/discussion";
import { useUser } from "../../../contexts/UserContext";
import discussionService from "../../../services/discussion";
import NewDiscussion from "./components/NewDiscussion";
import DiscussionDetail from "./components/DiscussionDetail";
import TeacherDiscussions from "./components/TeacherDiscussions";

const { Search } = Input;
const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;
const { TabPane } = Tabs;

// 真实教师姓名
const REAL_TEACHER_NAMES = [
  "王建国", "李雅琴", "张伟", "陈志强", "刘梦华", "杨志明", "赵丽华", "孙志强", 
  "周雅琴", "吴建国", "徐梦华", "朱志明", "胡丽华", "郭志强", "何雅琴",
  "马建国", "韩梦华", "郑志明", "冯丽华", "曹志强", "彭雅琴", "董建国", "袁梦华",
  "潘志明", "田丽华", "姜志强", "魏雅琴", "蒋建国", "韦梦华", "傅志明"
];

// 真实学生姓名
const REAL_STUDENT_NAMES = [
  "李明轩", "王雨涵", "张浩然", "刘雅琪", "陈思远", "杨梦瑶", "赵天宇", "孙诗涵",
  "周博文", "吴欣怡", "徐子轩", "朱雨桐", "胡志强", "郭雅婷", "何俊杰",
  "马晓雯", "韩志豪", "郑雅文", "冯浩然", "曹梦琪", "彭志强", "董雅涵", "袁博文",
  "潘雨桐", "田志豪", "姜雅文", "魏浩然", "蒋梦琪", "韦志强", "傅雅涵",
  "沈博文", "卢雨桐", "姚志豪", "钱雅文", "汪浩然", "田梦琪", "任志强", "武雅涵",
  "戴博文", "贾雨桐", "夏志豪", "钟雅文", "邱浩然", "骆梦琪", "高志强", "蔡雅涵",
  "樊博文", "胡雨桐", "凌志豪", "霍雅文", "虞浩然", "万梦琪", "支志强", "柯雅涵",
  "昝博文", "管雨桐", "卢志豪", "莫雅文", "经浩然", "房梦琪", "缪志强", "干雅涵",
  "解博文", "应雨桐", "宗志豪", "丁雅文", "宣浩然", "贲梦琪", "邓志强", "郁雅涵",
  "单博文", "杭雨桐", "洪志豪", "包雅文", "诸浩然", "左梦琪", "石志强", "崔雅涵",
  "吉博文", "钮雨桐", "龚志豪", "程雅文", "嵇浩然", "邢梦琪", "滑志强", "裴雅涵",
  "陆博文", "荣雨桐", "翁志豪", "荀雅文", "羊浩然", "於梦琪", "惠志强", "甄雅涵",
  "曲博文", "家雨桐", "封志豪", "芮雅文", "羿浩然", "储梦琪", "靳志强", "汲雅涵",
  "邴博文", "糜雨桐", "松志豪", "井雅文", "段浩然", "富梦琪", "巫志强", "乌雅涵",
  "焦博文", "巴雨桐", "弓志豪", "牧雅文", "隗浩然", "山梦琪", "谷志强", "车雅涵",
  "侯博文", "宓雨桐", "蓬志豪", "全雅文", "郗浩然", "班梦琪", "仰志强", "秋雅涵",
  "仲博文", "伊雨桐", "宫志豪", "宁雅文", "仇浩然", "栾梦琪", "暴志强", "甘雅涵",
  "钭博文", "厉雨桐", "戎志豪", "祖雅文", "武浩然", "符梦琪", "刘志强", "景雅涵",
  "詹博文", "束雨桐", "龙志豪", "叶雅文", "幸浩然", "司梦琪", "韶志强", "郜雅涵",
  "黎博文", "蓟雨桐", "薄志豪", "印雅文", "宿浩然", "白梦琪", "怀志强", "蒲雅涵",
  "邰博文", "从雨桐", "鄂志豪", "索雅文", "咸浩然", "籍梦琪", "赖志强", "卓雅涵",
  "蔺博文", "屠雨桐", "蒙志豪", "池雅文", "乔浩然", "阴梦琪", "郁志强", "胥雅涵",
  "能博文", "苍雨桐", "双志豪", "闻雅文", "莘浩然", "党梦琪", "翟志强", "谭雅涵",
  "贡博文", "劳雨桐", "逄志豪", "姬雅文", "申浩然", "扶梦琪", "堵志强", "冉雅涵",
  "宰博文", "郦雨桐", "雍志豪", "舄雅文", "璩浩然", "桑梦琪", "桂志强", "濮雅涵",
  "牛博文", "寿雨桐", "通志豪", "边雅文", "扈浩然", "燕梦琪", "冀志强", "郏雅涵",
  "浦博文", "尚雨桐", "农志豪", "温雅文", "别浩然", "庄梦琪", "晏志强", "柴雅涵",
  "瞿博文", "阎雨桐", "充志豪", "慕雅文", "连浩然", "茹梦琪", "习志强", "宦雅涵",
  "艾博文", "鱼雨桐", "容志豪", "向雅文", "古浩然", "易梦琪", "慎志强", "戈雅涵",
  "廖博文", "庾雨桐", "终志豪", "暨雅文", "居浩然", "衡梦琪", "步志强", "都雅涵",
  "耿博文", "满雨桐", "弘志豪", "匡雅文", "国浩然", "文梦琪", "寇志强", "广雅涵",
  "禄博文", "阙雨桐", "东志豪", "欧雅文", "殳浩然", "沃梦琪", "利志强", "蔚雅涵",
  "越博文", "夔雨桐", "隆志豪", "师雅文", "巩浩然", "厍梦琪", "聂志强", "晁雅涵",
  "勾博文", "敖雨桐", "融志豪", "冷雅文", "訾浩然", "辛梦琪", "阚志强", "那雅涵",
  "简博文", "饶雨桐", "空志豪", "曾雅文", "毋浩然", "沙梦琪", "乜志强", "养雅涵",
  "鞠博文", "须雨桐", "丰志豪", "巢雅文", "关浩然", "蒯梦琪", "相志强", "查雅涵",
  "后博文", "荆雨桐", "红志豪", "游雅文", "竺浩然", "权梦琪", "逯志强", "盖雅涵",
  "益博文", "桓雨桐", "公志豪", "万俟雅文", "司马浩然", "上官梦琪", "欧阳志强", "夏侯雅涵",
  "诸葛博文", "闻人雨桐", "东方志豪", "赫连雅文", "皇甫浩然", "尉迟梦琪", "公羊志强", "澹台雅涵",
  "公冶博文", "宗政雨桐", "濮阳志豪", "淳于雅文", "单于浩然", "太叔梦琪", "申屠志强", "公孙雅涵",
  "仲孙博文", "轩辕雨桐", "令狐志豪", "钟离雅文", "宇文浩然", "长孙梦琪", "慕容志强", "司徒雅涵",
  "司空博文", "亓官雨桐", "司寇志豪", "仉督雅文", "子车浩然", "颛孙梦琪", "端木志强", "巫马雅涵",
  "公西博文", "漆雕雨桐", "乐正志豪", "壤驷雅文", "公良浩然", "拓跋梦琪", "夹谷志强", "晋雅涵",
  "楚博文", "闫雨桐", "法志豪", "汝雅文", "鄢浩然", "涂梦琪", "钦志强", "段干雅涵",
  "百里博文", "东郭雨桐", "南门志豪", "呼延雅文", "归海浩然", "羊舌梦琪", "微生志强", "岳雅涵",
  "帅博文", "缑雨桐", "亢志豪", "况雅文", "后浩然", "有梦琪", "琴志强", "梁丘雅涵",
  "左丘博文", "东门雨桐", "西门志豪", "商雅文", "牟浩然", "佘梦琪", "佴志强", "伯雅涵",
  "赏博文", "南宫雨桐", "墨志豪", "哈雅文", "谯浩然", "笪梦琪", "年志强", "爱雅涵",
  "阳博文", "佟雨桐", "第五志豪", "言雅文", "福浩然", "百梦琪", "家志强", "姓雅涵"
];

// 根据用户角色生成默认头像
const getDefaultAvatar = (name: string, role: string) => {
  const hash = name.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  const seed = Math.abs(hash).toString();
  
  if (role === "teacher") {
    return `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=b6e3f4`;
  } else {
    return `https://api.dicebear.com/7.x/personas/svg?seed=${seed}&backgroundColor=ffdfbf`;
  }
};

// 生成真实的回复内容
const generateRealReplyContent = (topic: string, isTeacher: boolean, replyIndex: number): string => {
  const teacherReplies = {
    "如何提高学生的编程实践能力？": [
      "我建议采用项目驱动教学法，让学生在实际项目中应用理论知识。比如设计一个小型管理系统，涵盖链表、栈、队列等数据结构。这样可以让学生在实践中理解理论，提高动手能力。",
      "补充一下，可以让学生结对编程，互相学习。同时设置阶段性检查点，及时发现问题并指导。我还会定期举办编程竞赛，激发学生的学习兴趣。",
      "我采用的方法是分层教学，针对不同基础的学生制定不同的教学计划。基础好的学生可以挑战更复杂的项目，基础薄弱的学生从简单项目开始。",
      "建议建立在线编程平台，如LeetCode、牛客网等，让学生有更多练习机会。同时建立代码仓库，方便学生查看优秀代码，学习编程规范。",
      "我还会使用版本控制工具，培养学生的工程化思维。让学生学会团队协作，这对他们未来的工作很有帮助。"
    ],
    "数据结构课程的教学方法分享": [
      "数据结构确实比较抽象，我采用可视化教学法，使用动画演示各种数据结构的操作过程，学生理解起来更容易。",
      "我会设计一些生活中的例子来类比数据结构，比如用排队买票来解释队列，用书架来解释栈。这样学生更容易接受。",
      "建议分阶段教学，先讲概念，再讲实现，最后讲应用。每个阶段都要有相应的练习和测试。",
      "我还会让学生自己动手实现简单的数据结构，比如用数组实现栈和队列，这样他们能更好地理解原理。",
      "对于复杂的数据结构，我会用图形化的方式展示，比如二叉树的遍历过程，用不同颜色标记访问的节点。"
    ],
    "学生作业抄袭检测的有效方法": [
      "我使用多种工具进行检测，包括代码相似度分析工具和人工审查。同时建立代码规范，要求学生写注释和文档。",
      "建议采用开卷考试和项目答辩相结合的方式，让学生展示自己的理解和思考过程，而不是简单的代码复制。",
      "我会定期检查学生的代码提交历史，观察他们的学习过程。同时鼓励学生分享思路，而不是直接分享代码。",
      "建立学术诚信教育，让学生明白抄袭的危害。同时提供充足的练习资源，减少学生抄袭的动机。",
      "我还会使用在线编程平台，这些平台通常有防抄袭机制，可以检测代码相似度。"
    ],
    "在线教学平台的使用技巧": [
      "我推荐使用功能丰富的在线平台，如腾讯课堂、钉钉等。这些平台支持屏幕共享、录屏、互动等功能。",
      "建议提前测试平台功能，准备备用方案。同时建立学生群，方便课后交流和答疑。",
      "我会录制教学视频，方便学生反复观看。同时使用在线白板工具，进行实时演示和讲解。",
      "利用平台的签到、投票、问答等功能，增加课堂互动性。让学生积极参与，提高学习效果。",
      "建议建立学习档案，记录学生的学习轨迹和成绩变化，及时发现问题并调整教学策略。"
    ],
    "如何激发学生对算法的兴趣？": [
      "我采用游戏化教学，设计一些有趣的算法游戏，让学生在玩中学习。比如排序算法的可视化演示。",
      "建议从简单的问题开始，逐步增加难度。让学生感受到解决问题的成就感，激发学习兴趣。",
      "我会分享一些算法在现实生活中的应用，比如搜索引擎的排序算法，让学生明白算法的重要性。",
      "组织算法竞赛，让学生在竞争中提高。同时鼓励学生分享解题思路，互相学习。",
      "我还会使用一些有趣的算法题目，如汉诺塔、八皇后等经典问题，让学生体验算法的魅力。"
    ]
  };

  const studentReplies = {
    "如何提高学生的编程实践能力？": [
      "我觉得老师说得对，项目驱动教学确实很有效。我在做学生管理系统项目时，对数据结构的理解更深入了。",
      "结对编程真的很有帮助，我和同学一起做项目，互相学习了很多。希望老师能多安排这样的活动。",
      "我觉得分层教学很好，像我这样基础不太好的学生，可以从简单项目开始，慢慢提高。",
      "在线编程平台很有用，我经常在LeetCode上练习，感觉编程能力提升了很多。",
      "希望老师能多提供一些实际项目的案例，这样我们学习起来更有针对性。"
    ],
    "数据结构课程的教学方法分享": [
      "可视化教学真的很棒！老师用动画演示链表操作，我一下子就理解了。希望其他概念也能这样讲解。",
      "生活中的例子很形象，用排队买票解释队列，我一下子就记住了。老师的方法很有效。",
      "分阶段教学很好，每个阶段都有明确的目标和练习，学习起来很有条理。",
      "自己动手实现数据结构很有成就感，虽然开始有点困难，但做完后理解更深刻了。",
      "图形化展示很直观，特别是二叉树遍历，用不同颜色标记，一目了然。"
    ],
    "学生作业抄袭检测的有效方法": [
      "我觉得开卷考试和答辩的方式很好，这样能真正检验我们的理解程度，而不是记忆能力。",
      "代码提交历史检查很公平，能反映真实的学习过程。希望老师能多关注我们的学习轨迹。",
      "学术诚信教育很重要，我明白了抄袭的危害。现在我会独立思考，遇到问题先自己尝试解决。",
      "在线平台的防抄袭机制很有效，这样能保证作业的公平性。",
      "希望老师能提供更多的练习资源，这样我们就不需要抄袭了。"
    ],
    "在线教学平台的使用技巧": [
      "在线教学很方便，可以反复观看视频，不懂的地方可以暂停思考。",
      "屏幕共享功能很好，老师可以实时演示代码，我们看得更清楚。",
      "在线白板很实用，老师可以画图解释概念，比纯文字讲解更容易理解。",
      "互动功能增加了课堂的趣味性，投票和问答让课堂更活跃。",
      "学习档案很有用，可以清楚地看到自己的进步，很有成就感。"
    ],
    "如何激发学生对算法的兴趣？": [
      "算法游戏很有趣，特别是排序算法的可视化，让我对算法产生了兴趣。",
      "从简单问题开始很好，我感受到了解决问题的成就感，现在很喜欢算法课。",
      "算法在生活中的应用很神奇，比如搜索引擎的排序，让我明白了算法的重要性。",
      "算法竞赛很有挑战性，虽然我成绩不是很好，但参与过程很有趣。",
      "经典算法题目很有意思，比如汉诺塔，虽然复杂，但解决后很有成就感。"
    ]
  };

  const replies = isTeacher ? teacherReplies : studentReplies;
  const topicReplies = replies[topic as keyof typeof replies] || replies["如何提高学生的编程实践能力？"];
  
  return topicReplies[replyIndex % topicReplies.length];
};

// 教师端专用样式组件
const TeacherStyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
    color: #1890ff;
  }
  .ant-card-head {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    .ant-card-head-title {
      color: white;
    }
  }
`;

const TeacherReplyForm = styled(Form)`
  margin-top: 16px;
  .ant-form-item:last-child {
    margin-bottom: 0;
  }
  .ant-input {
    border-color: #1890ff;
  }
  .ant-btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
  }
`;

const TeacherAIReply = styled.div`
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  padding: 16px;
  border-radius: 8px;
  margin: 16px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  
  .ant-typography {
    color: white;
  }
`;

const TeacherReply = styled.div`
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px;
  border-radius: 8px;
  margin: 16px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  
  .ant-typography {
    color: white;
  }
  
  .ant-tag {
    background: rgba(255, 255, 255, 0.2);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
  }
`;

const TeacherNotice = styled(Alert)`
  margin-bottom: 24px;
  border: 2px solid #1890ff;
  .ant-alert-icon {
    color: #1890ff;
  }
`;

const TeacherStatsCard = styled(Card)`
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  
  .ant-statistic-title {
    color: rgba(255, 255, 255, 0.8);
  }
  
  .ant-statistic-content {
    color: white;
  }
`;

const TeacherDiscussion: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [discussions, setDiscussions] = useState<DiscussionPost[]>([]);
  const [filter, setFilter] = useState<DiscussionFilter>({
    sortBy: "latest",
  });
  const [isNewDiscussionVisible, setIsNewDiscussionVisible] = useState(false);
  const [selectedDiscussion, setSelectedDiscussion] = useState<string>();
  const [replyForm] = Form.useForm();
  const [likedDiscussions, setLikedDiscussions] = useState<Set<string>>(new Set());
  const [activeTab, setActiveTab] = useState("all");

  useEffect(() => {
    loadDiscussions();
  }, [filter]);

  const loadDiscussions = async () => {
    setLoading(true);
    try {
      // 生成教师端专用的模拟数据
      const generateTeacherMockDiscussions = (): DiscussionPost[] => {
        const teacherTopics = [
          "如何提高学生的编程实践能力？",
          "数据结构课程的教学方法分享",
          "学生作业抄袭检测的有效方法",
          "在线教学平台的使用技巧",
          "如何激发学生对算法的兴趣？",
          "课程设计项目的评分标准讨论",
          "学生编程基础薄弱怎么办？",
          "实验课教学经验分享",
          "如何平衡理论与实践教学？",
          "学生期末复习指导策略",
          "编程竞赛培训方法探讨",
          "课程思政在计算机课程中的融入",
          "学生创新能力培养实践",
          "教学资源建设经验分享",
          "学生心理辅导在技术教学中的作用",
          "在线考试系统的使用体验",
          "学生团队协作能力培养",
          "课程改革与创新实践",
          "学生就业指导经验分享",
          "教学反思与改进方法",
          "学生自主学习能力培养",
          "课程评价体系优化建议",
          "学生科研能力培养实践",
          "教学信息化建设经验",
          "学生职业规划指导方法",
          "课程国际化建设探讨",
          "学生创新创业教育实践",
          "教学质量提升策略",
          "学生综合素质评价方法",
          "课程思政建设经验分享",
          "学生实践能力培养模式",
          "教学团队建设经验",
          "学生学术诚信教育",
          "课程资源共建共享",
          "学生国际化视野培养",
          "教学创新实践案例",
          "学生职业素养培养",
          "课程建设质量保障",
          "学生社会责任感培养",
          "教学改革成果分享",
          "学生终身学习能力培养",
          "课程特色建设经验",
          "学生批判性思维培养",
          "教学效果评估方法",
          "学生领导力培养实践",
          "课程可持续发展策略",
          "学生跨文化交际能力培养",
          "教学科研融合发展",
          "学生社会适应能力培养",
          "课程品牌建设经验",
          "学生全球胜任力培养"
        ];

        const teacherContents = [
          "在教学过程中发现学生的编程实践能力普遍较弱，想请教各位老师有什么好的教学方法可以分享？",
          "数据结构是计算机专业的基础课程，但学生普遍反映难度较大，大家有什么有效的教学方法吗？",
          "最近发现学生作业抄袭现象比较严重，想了解其他老师是如何进行检测和预防的？",
          "在线教学平台功能越来越丰富，想和大家分享一下使用技巧和最佳实践。",
          "算法课程比较抽象，学生兴趣不高，有什么方法可以激发学生的学习兴趣？",
          "课程设计项目是检验学生综合能力的重要环节，想讨论一下评分标准的制定。",
          "有些学生编程基础很薄弱，跟不上课程进度，大家有什么好的辅导方法？",
          "实验课是理论联系实际的重要环节，想分享一些教学经验和改进建议。",
          "计算机课程既要注重理论教学，又要培养学生的实践能力，如何平衡这两者？",
          "期末考试临近，想了解其他老师是如何指导学生复习的？"
        ];

        const teacherTags = [
          ["教学方法", "编程实践", "能力培养"],
          ["数据结构", "教学经验", "课程设计"],
          ["作业管理", "学术诚信", "检测方法"],
          ["在线教学", "平台使用", "教学技巧"],
          ["算法教学", "兴趣培养", "教学方法"],
          ["课程设计", "评分标准", "项目指导"],
          ["基础薄弱", "辅导方法", "因材施教"],
          ["实验教学", "实践能力", "教学经验"],
          ["理论实践", "教学平衡", "课程设计"],
          ["期末复习", "学习指导", "考试准备"],
          ["竞赛培训", "编程竞赛", "能力提升"],
          ["课程思政", "思政教育", "价值引领"],
          ["创新能力", "创新教育", "实践培养"],
          ["教学资源", "资源建设", "共享平台"],
          ["心理辅导", "学生关怀", "教学支持"],
          ["在线考试", "考试系统", "技术应用"],
          ["团队协作", "协作能力", "项目实践"],
          ["课程改革", "教学创新", "改革实践"],
          ["就业指导", "职业规划", "就业服务"],
          ["教学反思", "教学改进", "质量提升"],
          ["自主学习", "学习能力", "培养方法"],
          ["评价体系", "课程评价", "体系优化"],
          ["科研能力", "科研培养", "学术训练"],
          ["教学信息化", "信息化建设", "技术应用"],
          ["职业规划", "规划指导", "生涯发展"],
          ["课程国际化", "国际化建设", "国际视野"],
          ["创新创业", "创新教育", "创业实践"],
          ["教学质量", "质量提升", "教学改进"],
          ["综合素质", "素质评价", "全面发展"],
          ["课程思政", "思政建设", "价值教育"],
          ["实践能力", "能力培养", "实践教学"],
          ["教学团队", "团队建设", "协作教学"],
          ["学术诚信", "诚信教育", "学风建设"],
          ["资源共建", "资源共享", "平台建设"],
          ["国际化视野", "国际视野", "跨文化"],
          ["教学创新", "创新实践", "改革案例"],
          ["职业素养", "素养培养", "职业发展"],
          ["质量保障", "保障体系", "质量监控"],
          ["社会责任感", "责任教育", "社会担当"],
          ["教学改革", "改革成果", "创新分享"],
          ["终身学习", "学习能力", "持续发展"],
          ["课程特色", "特色建设", "品牌打造"],
          ["批判性思维", "思维培养", "理性思考"],
          ["效果评估", "评估方法", "质量评价"],
          ["领导力", "领导能力", "管理培养"],
          ["可持续发展", "持续发展", "长期规划"],
          ["跨文化交际", "交际能力", "文化理解"],
          ["教学科研", "科研融合", "学术发展"],
          ["社会适应", "适应能力", "社会融入"],
          ["课程品牌", "品牌建设", "特色打造"],
          ["全球胜任力", "胜任力培养", "国际竞争"]
        ];

        return Array.from({ length: 50 }, (_, index) => {
          const isTeacher = Math.random() > 0.3; // 30%概率是教师发布
          const authorName = isTeacher 
            ? REAL_TEACHER_NAMES[Math.floor(Math.random() * REAL_TEACHER_NAMES.length)]
            : REAL_STUDENT_NAMES[Math.floor(Math.random() * REAL_STUDENT_NAMES.length)];
          
          return {
            id: `discussion_${index + 1}`,
            title: teacherTopics[index % teacherTopics.length],
            content: teacherContents[index % teacherContents.length],
            author: {
              id: isTeacher ? `teacher_${index + 1}` : `student_${index + 1}`,
              name: authorName,
              role: isTeacher ? "teacher" : "student",
              avatar: getDefaultAvatar(authorName, isTeacher ? "teacher" : "student")
            },
            createTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
            views: Math.floor(Math.random() * 500) + 50,
            likes: Math.floor(Math.random() * 100) + 5,
            replies: Array.from({ length: Math.floor(Math.random() * 5) + 1 }, (_, replyIndex) => {
              const isTeacherReply = Math.random() > 0.4; // 60%概率是教师回复
              const replyAuthorName = isTeacherReply 
                ? REAL_TEACHER_NAMES[Math.floor(Math.random() * REAL_TEACHER_NAMES.length)]
                : REAL_STUDENT_NAMES[Math.floor(Math.random() * REAL_STUDENT_NAMES.length)];
              
              // 生成真实的回复内容
              const replyContent = generateRealReplyContent(teacherTopics[index % teacherTopics.length], isTeacherReply, replyIndex);
              
              return {
                id: `reply_${index}_${replyIndex}`,
                content: replyContent,
                author: {
                  id: isTeacherReply ? `teacher_reply_${replyIndex}` : `student_reply_${replyIndex}`,
                  name: replyAuthorName,
                  role: isTeacherReply ? "teacher" : "student",
                  avatar: getDefaultAvatar(replyAuthorName, isTeacherReply ? "teacher" : "student")
                },
                createTime: new Date(Date.now() - Math.random() * 3 * 24 * 60 * 60 * 1000).toISOString(),
                likes: Math.floor(Math.random() * 20) + 1
              };
            }),
            tags: teacherTags[index % teacherTags.length],
            isPinned: Math.random() > 0.8, // 20%概率置顶
            aiResponse: Math.random() > 0.6 ? {
              content: "作为AI助手，我建议从以下几个方面来改进教学：\n\n1. **因材施教**：根据学生基础差异制定不同的教学策略\n2. **实践导向**：增加动手实践环节，提高学生参与度\n3. **互动教学**：采用讨论、案例分析等互动式教学方法\n4. **及时反馈**：建立有效的反馈机制，帮助学生及时调整学习方向",
              createTime: new Date(Date.now() - Math.random() * 24 * 60 * 60 * 1000).toISOString()
            } : undefined
          };
        });
      };

      const mockData = generateTeacherMockDiscussions();
      setDiscussions(mockData);
    } catch (error) {
      message.error("加载讨论列表失败");
      console.error("加载讨论列表失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setFilter({ ...filter, keyword: value });
  };

  const handleSortChange = (value: "latest" | "popular" | "mostReplies") => {
    setFilter({ ...filter, sortBy: value });
  };

  const handleTagClick = (tag: string) => {
    setFilter({
      ...filter,
      tags: filter.tags?.includes(tag)
        ? filter.tags.filter((t) => t !== tag)
        : [...(filter.tags || []), tag],
    });
  };

  const handleNewDiscussion = () => {
    setIsNewDiscussionVisible(true);
  };

  const handleNewDiscussionSubmit = async (values: {
    title: string;
    content: string;
    tags: string[];
    requestAIResponse: boolean;
  }) => {
    try {
      const newDiscussion: DiscussionPost = {
        id: `new_${Date.now()}`,
        title: values.title,
        content: values.content,
        author: {
          id: user?.id || "current_teacher",
          name: user?.name || "当前教师",
          role: "teacher",
          avatar: getDefaultAvatar(user?.name || "当前教师", "teacher")
        },
        createTime: new Date().toISOString(),
        views: 0,
        likes: 0,
        replies: [],
        tags: values.tags,
        isPinned: false,
        aiResponse: values.requestAIResponse ? {
          content: "AI正在分析您的问题，稍后将为您提供专业的教学建议...",
          createTime: new Date().toISOString()
        } : undefined
      };

      setDiscussions([newDiscussion, ...discussions]);
      setIsNewDiscussionVisible(false);
      message.success("发布成功！");
        } catch (error) {
      message.error("发布失败，请重试");
      console.error("发布讨论失败:", error);
    }
  };

  const handleLike = async (discussionId: string) => {
    const newLikedDiscussions = new Set(likedDiscussions);
    const isLiked = newLikedDiscussions.has(discussionId);
    
    if (isLiked) {
      newLikedDiscussions.delete(discussionId);
    } else {
      newLikedDiscussions.add(discussionId);
    }
    setLikedDiscussions(newLikedDiscussions);

    // 更新讨论的点赞数
    setDiscussions(discussions.map(discussion => {
      if (discussion.id === discussionId) {
        return {
          ...discussion,
          likes: isLiked ? discussion.likes - 1 : discussion.likes + 1
        };
      }
      return discussion;
    }));

    message.success(isLiked ? "已取消点赞" : "点赞成功");
  };

  const handleView = (discussionId: string) => {
    // 增加浏览量
    setDiscussions(discussions.map(discussion => {
      if (discussion.id === discussionId) {
        return {
          ...discussion,
          views: discussion.views + 1
        };
      }
      return discussion;
    }));
    setSelectedDiscussion(discussionId);
  };

  const handleViewReplies = (discussionId: string) => {
    // 直接打开评论区，不增加浏览量
    setSelectedDiscussion(discussionId);
  };

  const handleReply = async (discussionId: string) => {
    try {
      const values = await replyForm.validateFields();
      const newReply: DiscussionReply = {
        id: `reply_${Date.now()}`,
        content: values.reply,
        author: {
          id: user?.id || "current_teacher",
          name: user?.name || "当前教师",
          role: "teacher",
          avatar: getDefaultAvatar(user?.name || "当前教师", "teacher")
        },
        createTime: new Date().toISOString(),
        likes: 0
      };

      setDiscussions(discussions.map(discussion => {
        if (discussion.id === discussionId) {
          return {
            ...discussion,
            replies: [...discussion.replies, newReply]
          };
        }
        return discussion;
      }));

      replyForm.resetFields();
      message.success("回复成功！");
    } catch (error) {
      message.error("回复失败，请重试");
      console.error("回复失败:", error);
    }
  };

  // 教师管理功能
  const handleDeleteDiscussion = (discussionId: string) => {
    Modal.confirm({
      title: "确认删除讨论",
      content: "删除后将无法恢复，是否确认删除？",
      okText: "确认删除",
      cancelText: "取消",
      okType: "danger",
      onOk: () => {
        setDiscussions(discussions.filter(d => d.id !== discussionId));
        message.success("讨论已删除");
      }
    });
  };

  const handleDeleteReply = (discussionId: string, replyId: string) => {
    Modal.confirm({
      title: "确认删除回复",
      content: "删除后将无法恢复，是否确认删除？",
      okText: "确认删除",
      cancelText: "取消",
      okType: "danger",
      onOk: () => {
        setDiscussions(discussions.map(discussion => {
          if (discussion.id === discussionId) {
            return {
              ...discussion,
              replies: discussion.replies.filter(reply => reply.id !== replyId)
            };
          }
          return discussion;
        }));
        message.success("回复已删除");
      }
    });
  };

  const handlePinDiscussion = (discussionId: string) => {
    setDiscussions(discussions.map(discussion => {
      if (discussion.id === discussionId) {
        return {
          ...discussion,
          isPinned: !discussion.isPinned
        };
      }
      return discussion;
    }));
    message.success("置顶状态已更新");
  };

  const handleFlagDiscussion = (discussionId: string) => {
    message.success("讨论已标记为重要");
  };

  const handleRegenerateAIResponse = async (discussionId: string) => {
    try {
      const discussion = discussions.find(d => d.id === discussionId);
      if (!discussion) return;

      message.loading("AI正在重新生成回复...", 0);
      
      // 模拟AI重新生成
      setTimeout(() => {
        const newAIResponse = {
          content: `基于您的问题，我重新分析后建议：\n\n**教学策略调整：**\n1. 采用分层教学，针对不同基础学生制定不同教学计划\n2. 增加实践环节，让学生在实际项目中应用理论\n3. 建立学习小组，促进学生互助学习\n4. 定期进行学习评估，及时调整教学方向\n\n**具体实施建议：**\n- 每周安排2-3次实践课\n- 建立学生档案，记录学习进度\n- 设置阶段性目标，激励学生持续学习\n- 鼓励学生参与编程竞赛，提升实践能力`,
          createTime: new Date().toISOString()
        };

        setDiscussions(discussions.map(d => {
          if (d.id === discussionId) {
            return {
              ...d,
              aiResponse: newAIResponse
            };
          }
          return d;
        }));

        message.destroy();
        message.success("AI回复已重新生成");
      }, 2000);
    } catch (error) {
      message.error("AI回复生成失败");
    }
  };

  const renderAllDiscussions = () => (
    <List
      loading={loading}
      dataSource={discussions}
      renderItem={(discussion) => {
        const discussionMenuItems = [
          {
            key: "view",
            label: "查看详情",
            icon: <EyeOutlined />,
            onClick: () => handleView(discussion.id)
          },
          {
            key: "pin",
            label: discussion.isPinned ? "取消置顶" : "置顶",
            icon: <PushpinOutlined />,
            onClick: () => handlePinDiscussion(discussion.id)
          },
          {
            key: "flag",
            label: "标记重要",
            icon: <FlagOutlined />,
            onClick: () => handleFlagDiscussion(discussion.id)
          },
          {
            key: "regenerate",
            label: "重新生成AI回复",
            icon: <RobotOutlined />,
            onClick: () => handleRegenerateAIResponse(discussion.id),
            disabled: !discussion.aiResponse
          },
          {
            type: "divider" as const
          },
          {
            key: "delete",
            label: "删除讨论",
            icon: <DeleteOutlined />,
            danger: true,
            onClick: () => handleDeleteDiscussion(discussion.id)
          }
        ];

        return (
          <TeacherStyledCard
            key={discussion.id}
            hoverable
            actions={[
              <Dropdown
                menu={{ items: discussionMenuItems }}
                trigger={["click"]}
                placement="bottomRight"
              >
                <Tooltip title="更多操作">
                  <MoreOutlined />
                </Tooltip>
              </Dropdown>
            ]}
          >
          <List.Item>
            <List.Item.Meta
              avatar={
                <Avatar
                  src={discussion.author.avatar}
                  icon={<UserOutlined />}
                  style={{
                    backgroundColor: discussion.author.role === "teacher" ? "#1890ff" : "#52c41a"
                  }}
                />
              }
              title={
        <Space>
                  {discussion.isPinned && (
            <Tooltip title="已置顶">
              <PushpinOutlined style={{ color: "#1890ff" }} />
            </Tooltip>
          )}
                  <a onClick={() => handleView(discussion.id)}>{discussion.title}</a>
                  {discussion.author.role === "teacher" && (
                    <Tag icon={<CrownOutlined />} color="gold">
                      教师
                    </Tag>
                  )}
                  {discussion.aiResponse && (
            <Tag icon={<RobotOutlined />} color="purple">
              AI已回复
            </Tag>
          )}
        </Space>
              }
              description={
                <Space direction="vertical" size="small" style={{ width: "100%" }}>
                  <Space>
                    <Text strong>{discussion.author.name}</Text>
                    <Text type="secondary">{discussion.createTime}</Text>
                  </Space>
                  <Paragraph ellipsis={{ rows: 2 }}>{discussion.content}</Paragraph>
                  <Space>
                    {discussion.tags.map((tag) => (
                      <Tag
                        key={tag}
                        color={filter.tags?.includes(tag) ? "blue" : undefined}
                        style={{ cursor: "pointer" }}
                        onClick={() => handleTagClick(tag)}
                      >
                        {tag}
                      </Tag>
                    ))}
                  </Space>
                  <Space>
                    <Button
                      type="text"
                      size="small"
                      icon={<EyeOutlined />}
                      onClick={() => handleView(discussion.id)}
                      style={{ color: "#666", padding: "4px 8px" }}
                    >
                      {discussion.views} 浏览
                    </Button>
                    <Button
                      type="text"
                      size="small"
                      icon={likedDiscussions.has(discussion.id) ? <LikeFilled /> : <LikeOutlined />}
                      onClick={() => handleLike(discussion.id)}
                      style={{ 
                        color: likedDiscussions.has(discussion.id) ? "#1890ff" : "#666",
                        padding: "4px 8px"
                      }}
                    >
                      {discussion.likes} 点赞
                    </Button>
                    <Button
                      type="text"
                      size="small"
                      icon={<MessageOutlined />}
                      onClick={() => handleViewReplies(discussion.id)}
                      style={{ color: "#666", padding: "4px 8px" }}
                    >
                      {discussion.replies.length} 回复
                    </Button>
                  </Space>
                </Space>
              }
            />
          </List.Item>
        </TeacherStyledCard>
        );
      }}
    />
  );

  const renderTeacherDiscussions = () => (
    <List
      loading={loading}
      dataSource={discussions.filter(d => d.author.role === "teacher")}
      renderItem={(discussion) => (
        <TeacherStyledCard
          key={discussion.id}
          hoverable
          actions={[]}
        >
          <List.Item>
            <List.Item.Meta
              avatar={
                <Avatar
                  src={discussion.author.avatar}
                  icon={<UserOutlined />}
                  style={{ backgroundColor: "#1890ff" }}
                />
              }
              title={
        <Space>
                  {discussion.isPinned && (
                    <Tooltip title="已置顶">
                      <PushpinOutlined style={{ color: "#1890ff" }} />
                    </Tooltip>
                  )}
                  <a onClick={() => handleView(discussion.id)}>{discussion.title}</a>
                  <Tag icon={<CrownOutlined />} color="gold">
                    教师
                  </Tag>
                  {discussion.aiResponse && (
                    <Tag icon={<RobotOutlined />} color="purple">
                      AI已回复
          </Tag>
                  )}
                </Space>
              }
              description={
                <Space direction="vertical" size="small" style={{ width: "100%" }}>
                  <Space>
                    <Text strong>{discussion.author.name}</Text>
                    <Text type="secondary">{discussion.createTime}</Text>
        </Space>
                  <Paragraph ellipsis={{ rows: 2 }}>{discussion.content}</Paragraph>
        <Space>
                    {discussion.tags.map((tag) => (
            <Tag
              key={tag}
              color={filter.tags?.includes(tag) ? "blue" : undefined}
              style={{ cursor: "pointer" }}
              onClick={() => handleTagClick(tag)}
            >
              {tag}
            </Tag>
          ))}
        </Space>
                  <Space>
                    <Button
                      type="text"
                      size="small"
                      icon={<EyeOutlined />}
                      onClick={() => handleView(discussion.id)}
                      style={{ color: "#666", padding: "4px 8px" }}
                    >
                      {discussion.views} 浏览
                    </Button>
                    <Button
                      type="text"
                      size="small"
                      icon={likedDiscussions.has(discussion.id) ? <LikeFilled /> : <LikeOutlined />}
                      onClick={() => handleLike(discussion.id)}
                      style={{ 
                        color: likedDiscussions.has(discussion.id) ? "#1890ff" : "#666",
                        padding: "4px 8px"
                      }}
                    >
                      {discussion.likes} 点赞
                    </Button>
                    <Button
                      type="text"
                      size="small"
                      icon={<MessageOutlined />}
                      onClick={() => handleViewReplies(discussion.id)}
                      style={{ color: "#666", padding: "4px 8px" }}
                    >
                      {discussion.replies.length} 回复
                    </Button>
                  </Space>
                </Space>
              }
            />
          </List.Item>
        </TeacherStyledCard>
      )}
    />
  );

  const renderStudentQuestions = () => (
    <List
      loading={loading}
      dataSource={discussions.filter(d => d.author.role === "student")}
      renderItem={(discussion) => (
        <TeacherStyledCard
          key={discussion.id}
          hoverable
          actions={[]}
        >
          <List.Item>
            <List.Item.Meta
              avatar={
                <Avatar
                  src={discussion.author.avatar}
                  icon={<UserOutlined />}
                  style={{ backgroundColor: "#52c41a" }}
                />
              }
              title={
                <Space>
                  {discussion.isPinned && (
                    <Tooltip title="已置顶">
                      <PushpinOutlined style={{ color: "#1890ff" }} />
                    </Tooltip>
                  )}
                  <a onClick={() => handleView(discussion.id)}>{discussion.title}</a>
                  <Tag icon={<TeamOutlined />} color="green">
                    学生
                  </Tag>
                  {discussion.aiResponse && (
                    <Tag icon={<RobotOutlined />} color="purple">
                      AI已回复
                    </Tag>
                  )}
                </Space>
              }
              description={
                <Space direction="vertical" size="small" style={{ width: "100%" }}>
                  <Space>
                    <Text strong>{discussion.author.name}</Text>
                    <Text type="secondary">{discussion.createTime}</Text>
                  </Space>
                  <Paragraph ellipsis={{ rows: 2 }}>{discussion.content}</Paragraph>
        <Space>
                    {discussion.tags.map((tag) => (
                      <Tag
                        key={tag}
                        color={filter.tags?.includes(tag) ? "blue" : undefined}
                        style={{ cursor: "pointer" }}
                        onClick={() => handleTagClick(tag)}
                      >
                        {tag}
                      </Tag>
                    ))}
        </Space>
        <Space>
          <Button
                      type="text"
                      size="small"
                      icon={<EyeOutlined />}
                      onClick={() => handleView(discussion.id)}
                      style={{ color: "#666", padding: "4px 8px" }}
                    >
                      {discussion.views} 浏览
          </Button>
          <Button
                      type="text"
                      size="small"
                      icon={likedDiscussions.has(discussion.id) ? <LikeFilled /> : <LikeOutlined />}
                      onClick={() => handleLike(discussion.id)}
                      style={{ 
                        color: likedDiscussions.has(discussion.id) ? "#1890ff" : "#666",
                        padding: "4px 8px"
                      }}
                    >
                      {discussion.likes} 点赞
          </Button>
          <Button
                      type="text"
                      size="small"
                      icon={<MessageOutlined />}
                      onClick={() => handleViewReplies(discussion.id)}
                      style={{ color: "#666", padding: "4px 8px" }}
                    >
                      {discussion.replies.length} 回复
          </Button>
        </Space>
                </Space>
              }
            />
          </List.Item>
        </TeacherStyledCard>
      )}
    />
  );

  const renderStatistics = () => (
    <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
        <TeacherStatsCard>
            <Statistic
              title="总讨论数"
            value={discussions.length}
              prefix={<MessageOutlined />}
            />
        </TeacherStatsCard>
        </Col>
        <Col span={6}>
        <TeacherStatsCard>
            <Statistic
              title="今日新增"
            value={Math.floor(discussions.length * 0.1)}
            prefix={<BookOutlined />}
            />
        </TeacherStatsCard>
        </Col>
        <Col span={6}>
        <TeacherStatsCard>
            <Statistic
              title="待回复"
            value={discussions.filter(d => d.replies.length === 0).length}
            prefix={<ExclamationCircleOutlined />}
            />
        </TeacherStatsCard>
        </Col>
        <Col span={6}>
        <TeacherStatsCard>
            <Statistic
              title="AI回复率"
            value={Math.round((discussions.filter(d => d.aiResponse).length / discussions.length) * 100)}
              suffix="%"
              prefix={<RobotOutlined />}
            />
        </TeacherStatsCard>
        </Col>
      </Row>
  );

  return (
    <div style={{ padding: "24px" }}>
      <Title level={2} style={{ marginBottom: 24, color: "#1890ff" }}>
        <MessageOutlined /> 教师端讨论区
            </Title>



      {/* 统计信息 */}
      {renderStatistics()}

      {/* 操作栏 */}
      <Card style={{ marginBottom: 24 }}>
        <Row gutter={16} align="middle">
          <Col flex="auto">
          <Space>
            <Search
              placeholder="搜索讨论..."
              onSearch={handleSearch}
              style={{ width: 300 }}
            />
            <Select
              value={filter.sortBy}
              onChange={handleSortChange}
              style={{ width: 120 }}
              >
                <Select.Option value="latest">最新</Select.Option>
                <Select.Option value="popular">最热</Select.Option>
                <Select.Option value="mostReplies">回复最多</Select.Option>
              </Select>
          </Space>
          </Col>
          <Col>
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={handleNewDiscussion}
              style={{
                background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
                border: "none"
              }}
            >
              发布讨论
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 标签页 */}
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="全部讨论" key="all">
          {renderAllDiscussions()}
        </TabPane>
        <TabPane tab="教师交流" key="teacher">
          {renderTeacherDiscussions()}
        </TabPane>
        <TabPane tab="学生问题" key="student">
          {renderStudentQuestions()}
        </TabPane>
      </Tabs>

      {/* 发布新讨论 */}
      <NewDiscussion
        visible={isNewDiscussionVisible}
        onCancel={() => setIsNewDiscussionVisible(false)}
        onSubmit={handleNewDiscussionSubmit}
        isTeacher={true}
      />

      {/* 讨论详情 */}
      <DiscussionDetail
        discussionId={selectedDiscussion}
        discussion={discussions.find(d => d.id === selectedDiscussion)}
        onClose={() => setSelectedDiscussion(undefined)}
        likedDiscussions={likedDiscussions}
        onLikeChange={handleLike}
        isTeacher={true}
      />
    </div>
  );
};

export default TeacherDiscussion;
